<?php
class xRendererHtml {
    protected $file = '';
    protected $ctypes = array ('xml' => 'text/xml', 'json' => 'text/javascript', 'html' => 'text/html' );
    protected $ctype;
    protected $res;
    protected $rt;

    function __construct() {
        xLog::setErrorLevel(E_ALL);
        header ( 'Content-type: text/html; charset=utf-8' );
    }



    function out() {
        xLog::setErrorLevel(E_ALL);
        $requested = X::param ( 'page' );
        $xdyn = X::param('xdyn');
        if (!$xdyn) $xdyn = 'main';
        if (!$requested) $requested = 'index';
        
        $page = X::locate ( $xdyn.'.'.$requested . '-html.xslt' );

        X::notice("xdyn: $xdyn; page: $requested");
        if (!$page) $page = X::locate ( $xdyn.'.'.$requested . '.xslt' );
        if (!$page) {
            header('404 Not Found');
            $page = X::locate ( 'error.404.xslt' );
            $source = 'clear';
        }
        if (! $page) {
            X::fatal ( 'Unable to find page template `404.xpt`!', QConst::X_FILE_NOT_FOUND );
        }

        $xsl = file_get_contents($page);
        $xsl = preg_replace_callback("/import[^>#]+(##[^#]+#)/sim", 'cb', $xsl);
        $xsl = preg_replace_callback("/include[^>#]+(##[^#]+#)/sim", 'cbi', $xsl);
        $xsl = preg_replace_callback("/document[^>#]+(##[^#]+#)/sim", 'cbd', $xsl);
//                die($xsl);


//        $xslDoc = new DOMDocument ( );
//        if(!@$xslDoc->loadXML ( $xsl ))
//            Log::fatal("Unable to load xslt!");
//
//
//        $xmlDoc = new DOMDocument ( );
//        if (!@$xmlDoc->load(Styler::locate($xdyn.'.xml')))
//            if (!@$xmlDoc->load('xdyn://'.$xdyn.'.php'))
//                Log::fatal('Unable to load XDYN for `'.$xdyn.'`');
//
//        $proc = new XSLTProcessor ( );
//        $proc->importStylesheet ( $xslDoc );
//
//
        $res = xLibXSLT::transform(X::locate($xdyn.'.xml'), $xsl);
//        $res = $proc->transformToXML ( $xmlDoc );

        $res = html_entity_decode ( $res );

        return $res;
    }
}

function cb($matches) {
    //var_dump($matches);
    $file =str_replace('#', '', $matches[1]);
    $file = Styler::locate($file);
    return "import href='$file";
}

function cbd($matches) {
    //var_dump($matches);
    $file =str_replace('#', '', $matches[1]);
    $file = Styler::locate($file);
    return "document('$file";
}
function cbi($matches) {
    //var_dump($matches);
    $file =str_replace('#', '', $matches[1]);
    $file = X::locate($file);
    return "import href='$file";
}
?>